package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequirePermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void save(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public Permission get(Long id) {

        Permission permission = permissionMapper.selectByPrimaryKey(id);
        return permission;
    }

    @Override
    public List<Permission> listAll() {

        List<Permission> list = permissionMapper.selectAll();
        return list;
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        /*int count = permissionMapper.selectForCount(qo);
        if (count == 0) {
            PageResult<Permission> pageResult = new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count, Collections.emptyList());
            return pageResult;
        }

        //获取总页数
        int totalPage = count % qo.getPageSize()== 0
                ? count /qo.getPageSize() : count/ qo.getPageSize()+1;
        //判断当前页是否大于总页数,如果是,把总页数作为当前页查询分页结果集
        if (qo.getCurrentPage()>totalPage){
            qo.setCurrentPage(totalPage);
        }*/
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());

        List<Permission> permissions = permissionMapper.selectForList(qo);
        return new PageInfo<>(permissions);
    }

    @Autowired
    private ApplicationContext ac;//spring上下文对象

    @Override
    public void reload() {
        //把每个控制器中的贴了注解的方法转化为权限数据,并插入到数据库
        //查询数据库中已经有的权限表达式
        List<String> permissions = permissionMapper.selectAllExpression();
        //获取所有的控制器
        Map<String, Object> map = ac.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = map.values();
        //遍历获取每个控制器中的方法
        for (Object controller:controllers){
            //如果controller是普通的类,它的父类就object,object的方法没有贴注解,不影响效果但是效率不高
            //为了提高效率,判断是否是cglib代理,如果不是就跳过
            if (!AopUtils.isCglibProxy(controller)){
                continue;
            }

            Class<?> clazz = controller.getClass().getSuperclass();//用代理对象的父类来获取字节码对象
            //遍历获取到每个方法
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method :methods){
                //判断是否有贴自定义注解
                RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
                if (annotation!=null){
                    //从注解中获取权限相关的数据并封装为权限对象
                    String name = annotation.value()[1];
                    //方式一 注解获得
                    String expression = annotation.value()[0];
                    /*//方式二 反射拼接
                    String simpleName = clazz.getSimpleName();//EmployeeControl
                    simpleName.replace("Controller","" );//Employee
                    //String.valueOf(simpleName.charAt(0)).toLowerCase();//employee
                    simpleName = StringUtils.uncapitalize(simpleName);
                    String expression = simpleName+ ":" + method.getName();*/

                    if (!permissions.contains(expression)){//权限集合中不包括这个权限表达式,就需要插入

                        //保存插入到数据库中
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        permissionMapper.insert(permission);

                    }

                }



            }


        }



    }

    @Override
    public List<String> selectById(Long id) {
        return permissionMapper.selectById(id);
    }
}
